<template>
  <div class="marquee-container" :style="{height: height + 'px'}">
    <div class="marquee-scroller" ref="scroller">
      <div class="marquee-list" ref="container">
        <slot></slot>
      </div>
      <div class="marquee-list" ref="cloneContainer">
      </div>
    </div>
  </div>

</template>
<script>
export default{
  name: 'Marquee',
  data (){
    this.currentPos = 0;
    return {
      height: '',
      length: 0,
      currentIndex: 0,
      raf: null
    }
  },
  props: {
    animate: {
      type: Boolean,
      default: true
    }
  },
  mounted (){
    if (this.animate) {
      this.fixList();
      this.start();
    }

  },
  updated() {
    if (this.animate) {
      if (this.raf) {
        cancelAnimationFrame(this.raf);
      }
      this.fixList();
      this.start();
    }
  },
  destroyed () {
    cancelAnimationFrame(this.raf);
  },
  methods: {
    /**
     * TODO 可优化成recycleView
     * @description clone 列表
     * */
    fixList (){
      this.$refs.cloneContainer.innerHTML = this.$refs.container.innerHTML;
      this.$nextTick(()=>{
        // 用总高度/length，减小较小
        this.height = this.$refs.container.scrollHeight;
      });
    },
    /*
     * 启动轮播
     */
    start (){
      this.raf = requestAnimationFrame(() => {
        this.moveUp();
      });
    },
    moveUp () {
      this.currentPos +=0.5;
      this.setTransform(this.$refs.scroller, `translateY(-${this.currentPos}px)`);
      if (this.currentPos >= this.height) {
        this.currentPos = this.currentPos - this.height;
      }
      this.raf = requestAnimationFrame(() => this.moveUp());
    },

    setTransform (ele, val){
      ele.style.transform = val;
      ele.style.WebkitTransform = val;
      ele.style.MozTransform = val;
      ele.style.OTransform = val;
    }
  }
}
</script>
<style lang="scss" scoped>
.marquee-container{
  width: 100%;
  overflow: hidden;
  transform: translateZ(0);
  height: 100%;
  .marquee-list{
    padding: 0;
    margin: 0;
    width: 100%;
    height: auto;
  }
}
</style>